package com.kapukapu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kapukapu.common.api.user.dto.AuthUserDTO;
import com.kapukapu.user.entity.SysRole;
import com.kapukapu.user.entity.SysUser;
import com.kapukapu.user.mapper.SysUserMapper;
import com.kapukapu.user.service.SysRoleService;
import com.kapukapu.user.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sivan
 * @since 2020-03-16
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService {

    private final SysRoleService sysRoleService;

    public SysUserServiceImpl(SysRoleService sysRoleService) {
        this.sysRoleService = sysRoleService;
    }

    @Override
    public AuthUserDTO getUserByUsername(String username) {
        SysUser user = this.getOne(
            new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, username));

        if (!ObjectUtils.isEmpty(user)) {
            List<SysRole> roles = sysRoleService.getRolesByUserId(user.getId());
            List<String> roleKeys = roles.stream().map(SysRole::getKey)
                .collect(Collectors.toList());
            return new AuthUserDTO().setId(user.getId()).setName(user.getName())
                .setUsername(user.getUserName()).setPassword(user.getPassword())
                .setRoles(roleKeys);
        }

        return null;
    }
}
